package com.example.sq.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class MyAccessDeniedHandler implements AccessDeniedHandler {


    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
            throws IOException, ServletException
    {
        // 初始化授权异常响应数据
        Map<String, Object> result = new HashMap<>();
        result.put("message", "对不起，您无权访问");
        result.put("code", "403");
        result.put("accessDeniedException", accessDeniedException.getMessage());
        // 返回 403
        response.setStatus(HttpStatus.FORBIDDEN.value());
        // 设置响应数据格式为 JSON
        response.setContentType("application/json;charset=UTF-8");
        // 使用 Jackson 将 Map 转为 JSON 数据
        String resultStr = new ObjectMapper().writeValueAsString(result);
        // 返回客户端
        response.getWriter().write(resultStr);

    }

}
